博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【Java】登录操作中随机生成验证码的工具类
阅读量:5069 次
发布时间:2019-06-12

本文共 6476 字,大约阅读时间需要 21 分钟。

效果图:

工具类CreateImageCode.java:

import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.IOException;import java.io.OutputStream;import java.util.Random;import javax.imageio.ImageIO;public class CreateImageCode {    private int width = 70;    private int height = 27;    private int codeCount = 4;    // 干扰线数    //private int lineCount = 10;    // 验证码图片Buffer    // 验证码    private String code = null;    public String getCode() {        return code;    }    public void setCode(String code) {        this.code = code;    }    private BufferedImage buffImg = null;    Random random = new Random();    public CreateImageCode() {        createImage();    }    public CreateImageCode(int width, int height) {        this.width = width;        this.height = height;        createImage();    }    public CreateImageCode(int width, int height, int codeCount) {        this.width = width;        this.height = height;        this.codeCount = codeCount;        createImage();    }    public CreateImageCode(int width, int height, int codeCount, int lineCount) {        this.width = width;        this.height = height;        this.codeCount = codeCount;        //this.lineCount = lineCount;        createImage();    }    // 生成图片    private void createImage() {        int fontWidth = width / codeCount;// 字体宽度。        int fontHeight = height - 5;// 字体高度。        int codeY = height - 8;        // 得到图片        buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);        Graphics g = buffImg.getGraphics();        // 设置背景色        g.setColor(getRandColor(249, 250));        g.fillRect(0, 0, width, height);        // 设置边框        //g.setColor(getRandColor(200, 250));        //g.drawRect(1, 1, width - 2, height - 2);        // 设置字体        Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);        g.setFont(font);        /*// 设置干扰线        for (int i = 0; i < lineCount; i++) {            int x1 = random.nextInt(width);            int y1 = random.nextInt(height);            int x2 = random.nextInt(width);            int y2 = random.nextInt(height);            g.setColor(getRandColor(1, 255));            g.drawLine(x1, y1, x2, y2);        }*/        /*// 添加噪点        float yawpRate = 0.01f;// 噪声率        int area = (int) (yawpRate * width * height);        for (int i = 0; i < area; i++) {            int x = random.nextInt(width);            int y = random.nextInt(height);            buffImg.setRGB(x, y, random.nextInt(255));        }*/        String str1 = randomStr(codeCount);// 得到随机字符        this.code = str1;        for (int i = 0; i < codeCount; i++) {            String strRand = str1.substring(i, i + 1);            g.setColor(getRandColor(50, 250));            // g.drawString(a,x,y);            // a为要画出来的东西,x和y表示要画的东西最左侧字符的基线位于此图形上下文坐标系的 (x, y) 位置处            g.drawString(strRand, i * fontWidth + 3, codeY);        }    }    // 得到随机字符    private String randomStr(int n) {        String str1 = "1234567890";        String str2 = "";        int len = str1.length() - 1;        double r;        for (int i = 0; i < n; i++) {            r = (Math.random()) * len;            str2 = str2 + str1.charAt((int) r);        }        return str2;    }    // 得到随机颜色    private Color getRandColor(int fc, int bc) {
// 给定范围获得随机颜色 if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } public void write(OutputStream sos) throws IOException { ImageIO.write(buffImg, "png", sos); sos.close(); }}

在servlet中使用此工具类,输出验证码到网页:

package com.utils;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;@WebServlet(name = "GetImageCodeServlet",urlPatterns = {"/servlet/code.servlet"})public class GetImageCodeServlet extends HttpServlet {    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        this.doGet(request,response);    }    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        response.setContentType("image/jepg");        // 控制浏览器不要缓存        response.setDateHeader("expries", -1);        response.setHeader("Cache-Control", "no-cache");        response.setHeader("Pragma", "no-cache");        // 创建图片        CreateImageCode image = new CreateImageCode();        String str = image.getCode();        // 存入Session//        System.out.println("验证码为"+str);        request.getSession().setAttribute("code",str);        // 输出到网页        image.write(response.getOutputStream());    }}

JSP中在表单显示此图片(演示时不使用Ajax,直接将form提交到另一个servlet判断):

获取验证码

后台验证验证码的servlet:

package com.utils;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;@WebServlet(name = "CodeTestServlet" ,urlPatterns = {"/servlet/codeTest.servlet"})public class CodeTestServlet extends HttpServlet {    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        this.doGet(request,response);    }    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        String code = request.getParameter("code");        if (code.equals(request.getSession().getAttribute("code"))) {            System.out.println("验证成功,验证码为:" + request.getSession().getAttribute("code"));            // response.sendRedirect(getServletContext().getContextPath()+"/login.jsp");        }else{            System.out.println("验证失败");        }    }}

----

使用的是3.0的注解开发,web.xml中不需配置

若为maven项目,依赖为:

javax.servlet
javax.servlet-api
3.1.0
javax.servlet.jsp
javax.servlet.jsp-api
2.3.1

 

转载于:https://www.cnblogs.com/to-red/p/11260628.html

你可能感兴趣的文章
PHP上传RAR压缩包并解压目录
查看>>
Codeforces 719B Anatoly and Cockroaches
查看>>
jenkins常用插件汇总
查看>>
c# 泛型+反射
查看>>
第九章 前后查找
查看>>
Python学习资料
查看>>
多服务器操作利器 - Polysh
查看>>
[LeetCode] Candy
查看>>
jQuery 自定义函数
查看>>
jquery datagrid 后台获取datatable处理成正确的json字符串
查看>>
ActiveMQ与spring整合
查看>>
web服务器
查看>>
F# 编程 借助 F# 构建 MVVM 应用程序
查看>>
网卡流量检测.py
查看>>
【转】Android的权限permission
查看>>
ajax
查看>>
poj1981 Circle and Points 单位圆覆盖问题
查看>>
POP的Stroke动画
查看>>
线程同步机制初识 【转载】
查看>>
SQL语句在查询分析器中可以执行,代码中不能执行
查看>>